<template>
  <div class="addfarmsStock">
    <div class="backFont"><el-button icon="el-icon-arrow-left" @click="back()">返回</el-button></div>
    <el-form
      :model="addForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      class="demo-ruleForm mt20 errorForm"
    >
      <el-form-item class="noRequire" label="*农资" prop="name">
        <!-- <el-input
          v-model="addForm.name"
          v-if="inputShow"
          class="widthInput"
          :disabled="true"
        >
        </el-input> -->
        <div class="farmStockListBox">
          <div
            v-if="addForm.name"
            class="farmStockList"
          >
            <!-- <div class="icon">
              <img src="../../assets/img/huafeiicon.png" alt="" />
            </div> -->
            <div class="content">
              <div class="farmStockName">
                <span>{{ addForm.name }}</span>
                <!-- <div class="landType">{{ addForm.typeFormat }}</div> -->
              </div>
              <div class="manufacturer">
                <div>
                  {{ addForm.manufacturer }}
                </div>
              </div>
            </div>
            <!-- 校验数组 -->
            <div class="num">
              规格：{{ addForm.specifications }}
            </div>
            <!-- <div class="del" @click="del(index)">
              <i class="el-icon-error"></i>
            </div> -->
          </div>
        </div>

        <el-button v-if="!this.addForm.id" type="primary"  class="greenBtn" :class="{addBtn:inputShow}" @click="addBtn()">{{
          this.addForm.name === null ? "添加农资" : "重新选择"
        }}</el-button>
      </el-form-item>
      <!-- <el-form-item label="规格">
        <el-input class="widthInput" v-model="addForm.specifications" :disabled="true">
        </el-input>
      </el-form-item> -->
      <el-form-item class="noRequire" label="*入库数量" prop="num">
        <el-input v-if="!$route.query.id" class="widthInput" v-model="addForm.num" type="number" :min="1" >
        </el-input>
        <div v-else class="greyColor">{{ addForm.num }}</div>
      </el-form-item>
      <!-- 入库类型字典 -->
      <el-form-item class="noRequire" label="*入库类型" prop="receiptType">
        <!-- <el-radio-group v-model="addForm.receiptType">
          <el-radio v-for="item in RKLX" :key="item.id" :label="item.code">{{item.name}}</el-radio>
        </el-radio-group> -->
        <div v-if="!$route.query.id">
          <el-button
            class="typeBtn"
            :class="addForm.receiptType === item.code && 'checkBoxAll'"
            @click="addForm.receiptType = item.code"
            v-for="item in RKLX"
            :key="item.id"
          >
            {{ item.name }}
          </el-button>
        </div>
        <div v-else class="greyColor">
          {{
            addForm.receiptType ? RKLX.find(item => {
              return addForm.receiptType === item.code ? item  : ''
            }).name : ''
          }}
        </div>
      </el-form-item>
      <el-form-item class="noRequire" label="*入库时间" prop="purchaseTime">
        <el-date-picker
          v-if="!$route.query.id"
          class="widthInput"
          v-model="addForm.purchaseTime"
          type="date"
          placeholder="选择日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
        <div v-else class="greyColor">{{ addForm.purchaseTime }}</div>
      </el-form-item>
      <el-form-item class="noRequire" label="*操作人" prop="purchaser">
        <el-select v-if="!$route.query.id" class="widthInput"  v-model="addForm.purchaser" placeholder="请选择">
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.name"
            :value="item.userId"
          >
          </el-option>
        </el-select>
        <div v-else class="greyColor">
          {{
            addForm.purchaser ? userList.find(item => {
              return addForm.userId === item.purchaser ? item  : ''
            }).name : ''
          }}
        </div>
      </el-form-item>
      <el-form-item label="凭证照片">
        <upload
          ref="upload"
          v-model="addForm.picture"
          :isShowTip="false"
          :limit="3">
        </upload>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          type="textarea"
          placeholder="请输入备注"
          v-model="addForm.remark"
          style="width: 700px"
          :rows="4"
          maxlength="100"
          show-word-limit
        >
        </el-input>
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >立即创建</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item> -->
    </el-form>
    <div class="submitBottom">
      <el-button
        size="small"
        class="editBtn editBtnNone"
        @click="back()"
        >取消</el-button
      >
      <el-button
        class="editBtn"
        type="primary"
        size="small"
        @click="submitForm('ruleForm')"
      >
        确定
      </el-button>
    </div>
    <!-- 农资弹窗 -->
    <el-dialog
      title="选择农资"
      :visible.sync="dialogVisible"
       width="1100px"
      :show-close="false"
      :before-close="handleClose"
      custom-class="farmsStockDialog"
    >
    <div class="dialogSearch" slot="title">
      <div class="searchFlex">
        <span class="searchType">选择农资</span>
        <!-- <el-select size="small"  @input="farmStockSearch()" v-model="keywordType" class="select"  clearable placeholder="请选择农资类型">
          <el-option
            v-for="item in NZZLlist"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select> -->
      </div>
      <div class="searchFlex">
        <el-input
          size="small"
          class="searchInp"
          @input="farmStockSearch()"
          suffix-icon="el-icon-search"
          v-model="params.name"
          placeholder="搜索农资"
        ></el-input>
        <i class="el-icon-close" @click="handleClose()"></i>
      </div>
    </div>
      <farmStockDialog
        ref="farmStockDialog"
        :farmStockList="farmStockList"
        @farmsStockData="farmsStockData"
        :getAgriculturalDict="getAgriculturalDict"
        :total="total"
      ></farmStockDialog>
    </el-dialog>
  </div>
</template>

<script>
import { getUserListApi, getSysSonDictListApi, getAgriculturalDictApi } from '@/api/dict'
import { AddFarmStockApi, delpictureApi, UpdateByFarmStockApi, getAgriculturalDetail } from '@/api/farmStock'
import upload from '@/views/agriMissionAdd/components/upload.vue'
import farmStockDialog from './components/farmStockDialog'
import {
  getFarmsStockInventoryApi
} from '@/api/mission'
export default {
  name: 'SevencolorUserIndex',
  components: {
    upload, // 上传组件
    farmStockDialog
  },

  data () {
    return {
      addForm: {
        baseId: 1,
        agriDicId: null, // 农资ID
        name: null, // 农资名称
        num: null, // 农资数量
        specifications: null,
        purchaser: null, // 入库人--字典
        purchaseTime: null, // 入库时间
        receiptType: null, // 入库类型--字典
        picture: '',
        remark: null,
        price: null, // 单价
        totalPrice: null // 总数
      },
      params: {
        name: '',
        current: 1,
        pageSize: 8
      }, // 农资字典查询参数
      total: null,
      baseId: 1,
      addMissionData: {},
      rules: {
        name: [{ required: true, message: '请选择农资', trigger: 'blur' }],
        num: [{ required: true, message: '请选择农资', trigger: 'blur' }],
        receiptType: [{ required: true, message: '请选入库类型', trigger: 'blur' }],
        purchaseTime: [{ required: true, message: '请选择入库时间', trigger: 'blur' }],
        purchaser: [
          { required: true, message: '请选择操作人', trigger: 'blur' }
        ]
      },
      options: [],
      userList: [], // 用户字典
      dialogVisible: false, // 农资弹窗
      farmStockList: [], // 农资字典,
      inputShow: false, // 添加农资按钮显示,
      RKLX: []// 入库类型
    }
  },
  computed: {
    pictureList () {
      return this.$store.getters.pictureList
    },
    landDetail () {
      return this.$store.getters.landDetail
    },
    missionDetail () {
      return this.$store.getters.missionDetail
    }
  },
  destroyed () {
    sessionStorage.removeItem('farmsStockAdd')
  },
  mounted () {
    this.addForm.baseId = this.$store.getters.userInfo.baseId
    this.baseId = this.$store.getters.userInfo.baseId
    this.getAgriculturalDict(this.params)
    this.addMissionData = this.$route.params
    this.getAddForm()
    // this.editForm()
    this.getUserList()
    this.getSysSonDictList()
  },
  methods: {
    async getAddForm () {
      if (sessionStorage.getItem('farmsStockAdd')) {
        this.addForm = JSON.parse(sessionStorage.getItem('farmsStockAdd'))
        return
      }
      if (!this.$route.query.id) {
        return
      }
      const res = await getAgriculturalDetail({ id: this.$route.query.id })
      this.addForm = res.data
    },
    // 字典接口
    async getAgriculturalDict (params) {
      // 农资字典
      const res = await getAgriculturalDictApi({ ...params, baseId: this.baseId })
      res.data.records.map(item => {
        item.agriDicId = item.id
      })
      this.farmStockList = res.data.records
      this.total = res.data.total
    },
    // 农资搜索
    farmStockSearch () {
      clearTimeout(this.setTime)
      this.setTime = setTimeout(() => {
        this.getAgriculturalDict(this.params)
      }, 300)
    },
    //
    async getSysSonDictList () {
      const res = await getSysSonDictListApi('RKLX')
      this.RKLX = res.data.reverse()
    },
    // 用户list
    async getUserList () {
      const res = await getUserListApi(this.baseId)
      // console.log(res)
      this.userList = res.data
    },
    // 返回
    back () {
      this.$router.go(-1)
    },
    addBtn () {
      this.dialogVisible = !this.dialogVisible
    },
    // 子组件事件--添加农资
    farmsStockData (data) {
      this.addForm.name = data.name
      this.addForm.agriDicId = data.id
      this.addForm.specifications = data.specifications
      this.addForm.typeFormat = data.typeFormat
      this.addForm.manufacturer = data.manufacturer
      this.addForm.agriType = data.typeCode // 农资类型
      this.addForm.type = 0
      this.inputShow = true
      this.dialogVisible = false
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.addForm.picture = this.pictureList.join(',')
          // this.addForm.num = +this.addForm.num
          if (this.$route.query.id) {
            await UpdateByFarmStockApi(this.addForm)
          } else {
            await AddFarmStockApi(this.addForm)
          }
          this.$message.success('提交成功!')
          this.$router.go(-1)
          this.addForm = this.$options.data().addForm
          // this.$router.push({
          //   path: '/shuzhongtian/farmsStock'
          // }) // 返回详情
        } else {
          this.$message.error('请正确填写')
          return false
        }
      })
    },
    // 操作人下拉事件
    onSelectChange (value) {
      const userInfo = this.userList.filter((item) => item.userName === value)
      // console.log(userInfo)
      this.addForm.participantsId = userInfo[0].userId
    },
    // 农资弹窗关闭
    handleClose () {
      this.dialogVisible = false
    },
    // 重置表单
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.$refs.upload.clearFiles()
      if (this.pictureList.length > 0) {
        for (let i = 0; i < this.pictureList.length; i++) {
          delpictureApi(this.pictureList[i])
        }
        this.$store.dispatch('mission/removePictureList')
      }
    },
    // 编辑
    editForm () {
      if (this.missionDetail && this.missionDetail.id) {
        this.addForm.code = this.missionDetail.code
        this.addForm.participants = this.missionDetail.participants
        this.addForm.time = this.missionDetail.time
        this.addForm.way = this.missionDetail.way
        if (this.missionDetail.picture !== undefined) {
          this.addForm.picture = this.missionDetail.picture.split(',')
            .map((picture) => picture)
        }
        this.addForm.remark = this.missionDetail.remark
      }
    }
  }
}
</script>
<style scoped lang="scss">
.addfarmsStock {
  width: 100%;
  background: #ffffff;
  position: relative;
}
.back {
  position: absolute;
  top: 5%;
  left: 5%;
}
.demo-ruleForm {
  margin-bottom: 100px;
}
.name {
  display: inline-block;
  ::v-deep .el-form-item__content {
    display: flex;
  }
  .addBtn {
    margin-left: .5208vw;
  }
}
::v-deep .farmsStockDialog {
  // width: 80.2083vw;
  // height: 40.4375vw * 0.834;
  background: #ffffff;
  border-radius: 20px 20px 20px 20px;
}
.dialogSearch {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .searchFlex {
    display: flex;
    align-items: center;
    .searchType {
      font-size: 20px;
      font-weight: bold;
      margin-right: 20px;
    }
    .searchInp {
      ::v-deep .el-input__inner {
        background: rgba(196, 196, 196, 0.15);
        border: none
      }
    }
    .el-icon-close {
      font-size: 24px;
      margin-left: 25px;
      color: #666666
    }
  }
}
.farmStockListBox {
  .farmStockList {
    width: 300px;
    background: #FAFAFA;
    border-radius: 4px;
    padding: 18px 20px 0 20px;
    // display: flex;
    margin-bottom: 0.5208vw;
    position: relative;
    .icon {
      width: 0.4rem;
      height: 0.4rem;
      margin-right: 1.0417vw;
      padding: 0.5208vw;
      align-items: center;
    }
    .content {
      white-space: nowrap;
      .farmStockName {
        // margin-bottom: 0.4167vw * 0.834;
        display: flex;
        font-size: 14px;
        font-weight: bold;
        align-items: center;
        line-height: 1;
        .landType {
          margin-left: 5px;
          padding: 3px 6px 4px 6px;
          height: unset;
          background: unset;
          border: 1px solid #00C586;
          border-radius: 2px;
          text-align: center;
          color: #00C586;
          font-size: 12px;
        }
      }
      .manufacturer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 12px;
        color: #999999;
        line-height: 1;
        margin-top: 15px;
      }
    }
    .num {
      // padding: 0 0.2604vw;
      margin-top: 15px;
      color: #00C586;
      font-weight: bold;
      border-top: 1px solid #E1E1E1;
      // width: 7.2917vw;
      // height: 2.0833vw * 0.834;
      // background: #ffffff;
      // border-radius: 8px 8px 8px 8px;
      // border: 1px solid #dcdedf;
      // position: relative;
      ::v-deep .el-input__inner {
        width: 160px !important;
        background-color: unset;
      }
      ::v-deep .el-form-item__content {
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
      ::v-deep .el-form-item {
        margin-bottom: 0
      }
      .el-input {
        width: 165px;
      }
      .el-form-item__content{
        display: flex;
        justify-content: flex-end;
        align-items: center;
      }
      .unit {
        position: absolute;
        right: 10%;
        height: 1.8vw * 0.834;
        font-size: 0.7292vw;
        top: -50%;
        color: #333;
      }
    }
    .del {
      width: 20px;
      height: 20px;
      position: absolute;
      right: -8px;
      top: -15px;
      i {
        font-size: 20px;
        color: #F76560;
      }
    }
  }
}
</style>
<style>
/* .el-dialog__header {
  background: #002a52;
  text-align: center;
} */
.el-dialog__title {
  border-left: 3px solid #19b560;
  padding: 0 0.5208vw;
  font-weight: 500;
}
</style>
